package caculate.tree;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-04-14 23:14
 **/
public class BuildTreeBySeriale {

    static Map<Integer, Integer> hashtable = new HashMap<>();

    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < inorder.length; i++) {
            hashtable.put(inorder[i], i);
        }

        return buildTree(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }

    public static void main(String[] args) {

       int[] preorder = {1, 2};
       int[] inorder = {2,1};

        TreeNode root = buildTree(preorder, inorder);
        System.out.println();
    }

    public static TreeNode buildTree(int[] preorder, int[] inorder, int pl, int pr, int il, int ir) {
        if (pl > pr || il > ir) {
            return null;
        }

        TreeNode root = new TreeNode(preorder[pl]);
        Integer rootIndex = hashtable.get(preorder[pl]);
        // 从中序遍历中知道左节点个数
        int leftNum = rootIndex - pl;
        root.left = buildTree(preorder, inorder, pl + 1, pl + leftNum, il, rootIndex - 1);
        root.right = buildTree(preorder, inorder, pl + leftNum + 1, pr, rootIndex + 1, ir);

        return root;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
